package se.cbb.misc;


/**
 * Computes Pearson's Correlation between two lists of scores with same members.
 * @author Raja Hashim Ali
 *
 */
public class Correlation {
	public static float getPearsonCorrelation(Float[] geneArr,Float[] ncArray){
		if(geneArr.length == 0 || ncArray.length == 0) 
			return (float) -1;
		
		float result = 0;
		float sum_sq_x = 0;
		float sum_sq_y = 0;
		float sum_coproduct = 0;
		float mean_x = geneArr[0];
		float mean_y = ncArray[0];
		for(int i=2;i<geneArr.length+1;i+=1){
			float sweep =(float)(i-1)/i;
			float delta_x = geneArr[i-1]-mean_x;
			float delta_y = ncArray[i-1]-mean_y;
			sum_sq_x += delta_x * delta_x * sweep;
			sum_sq_y += delta_y * delta_y * sweep;
			sum_coproduct += delta_x * delta_y * sweep;
			mean_x += delta_x / i;
			mean_y += delta_y / i;
		}
		float pop_sd_x = (float) Math.sqrt(sum_sq_x/geneArr.length);
		float pop_sd_y = (float) Math.sqrt(sum_sq_y/geneArr.length);
		float cov_x_y = sum_coproduct / geneArr.length;
		result = cov_x_y / (pop_sd_x*pop_sd_y);
		return result;
	}
}